package com.core.security;

import java.io.IOException; 

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.core.util.DspUtil;
import com.core.util.MD5;
import com.dsp.bean.User;
import com.dsp.services.UserService;

public class LoginAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
	Logger logger = Logger.getLogger(DspUtil.Log4J);
	private static final String username = "j_username";
	private static final String password = "j_password";
	private static final String valideno = "j_validatecode";

	UserService userService;

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		if (!request.getMethod().equals("POST")) {
			logger.error("Authentication method not supported: " + request.getMethod());
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}
		// checkValidateCode(request);

		String username = obtainUsername(request);
		String password = obtainPassword(request);
		password = new MD5().getMD5ofStr(password);

		if ("".equals(username) || "".equals(password)) {
			logger.debug(messages.getMessage("UsernameAndPassword.notEquals"));
			throw new AuthenticationServiceException(messages.getMessage("UsernameAndPassword.notEquals"));
		}

		User users = this.userService.findByUserName(username);

		if (users == null) {
			logger.debug(messages.getMessage("username.notexists", username));
			throw new AuthenticationServiceException(messages.getMessage("username.notexists", username));
		}
		if (username.equals(users.getUsername()) && password.equals(users.getPassword())) {

			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
					password);
			setDetails(request, authRequest);
			logger.info("用户:" + username + " , 登录成功");
			return this.getAuthenticationManager().authenticate(authRequest);
		}
		logger.debug(messages.getMessage("password.notEquals"));
		throw new AuthenticationServiceException(messages.getMessage("password.notEquals"));
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
			ServletException {
		final HttpServletRequest request = (HttpServletRequest) req;
		final HttpServletResponse response = (HttpServletResponse) res;
		String userName = request.getParameter("j_username");
		logger.info("登录:" + userName);
		/**UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
	    .getAuthentication()
	    .getPrincipal();*/
		String path = request.getRequestURI();
		if (request.getMethod().equals("POST")) {
			logger.info("1");
			super.doFilter(request, response, chain);
		} else {
			logger.info("2");
			chain.doFilter(request, response);
		}
	}
	
	protected void checkValidateCode(HttpServletRequest request) { 
		HttpSession session = request.getSession();
		
	    String sessionValidateCode = obtainSessionValidateCode(session); 
	    //让上一次的验证码失效
	    session.setAttribute("Code", null);
	    String validateCodeParameter = obtainValidateCodeParameter(request);  
	    if (DspUtil.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {
	        throw new AuthenticationServiceException(messages.getMessage("validateCode.notEquals"));  
	    }  
	}

	private String obtainValidateCodeParameter(HttpServletRequest request) {
		Object obj = request.getParameter(valideno);
		return null == obj ? "" : obj.toString();
	}

	protected String obtainSessionValidateCode(HttpSession session) {
		Object obj = session.getAttribute("Code");
		return null == obj ? "" : obj.toString();
	}

	@Override
	protected String obtainUsername(HttpServletRequest request) {
		Object obj = request.getParameter(username);
		return null == obj ? "" : obj.toString();
	}

	@Override
	protected String obtainPassword(HttpServletRequest request) {
		Object obj = request.getParameter(password);
		return null == obj ? "" : obj.toString();
	}

	/**
	 * @return the userService
	 */
	public UserService getUserService() {
		return userService;
	}

	/**
	 * @param userService
	 *            the userService to set
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
